package cn.zhengzhou.springbootmybatis.demo;

import cn.zhengzhou.springbootmybatis.pojo.Student;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class DemoCallable {
    public static void main(String[] args) {
        //3.创建一个Callable接口的实现类对象
        Callable<String> c1 = new MyCallable(100);
        //4.把Callable对像封装一个真正的线程任务对象FutureTask对象
        FutureTask<String> f1 = new FutureTask<>(c1);
        //5.FutureTask对象作为参数传给Thread
        Thread t1 = new Thread(f1);
        //6. 启动线程
        t1.start();

        Callable<String> c2 = new MyCallable(50);

        FutureTask<String> f2 = new FutureTask<>(c2);

        Thread t2 = new Thread(f2);

        t2.start();

        try {
            System.out.println(f1.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(f2.get());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

//1.实现callable接口  有返回值
class MyCallable implements Callable<String> {
    //定义常量
    private int n;

    public MyCallable(int n) {

        this.n = n;
    }

    //重写call方法
    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return "子线程计算1+"+ n +"的和是：" + sum;
    }
}